<template>
    <div class="dashboard-resource">
        <div class="resource-header">
            <div class="resource-type">
                <div class="resource-type-item" :class="{ 'active': selected === item.key }" 
                    v-for="item in apiList" @click="selectType( item )">
                    <div class="resource-type-item-legend" :style="{ 'background-color': item.color }"></div>
                    <span>{{ item.name }}</span>
                </div>
            </div>
            <div class="resource-timerange">
                <div class="resouce-timerange-box">
                    <div class="resource-timerange-item" :class="{ 'active': rangeSelected === item.key }"
                        v-for="item in rangeList" @click="selectRange( item )">
                        <span>{{ item.name }}</span>
                    </div>
                </div>
            </div>
        </div>
        <div class="resource-content">
            <div class="resouce-loading" v-show="pending">
                <i class="iconfont icon-loading icon-spin"></i>
            </div>
            <div class="resource-chart" ref="chart"></div>
        </div>
    </div>
</template>

<script>
import Vue from 'vue'
import echarts from 'echarts/lib/echarts'
import 'echarts/lib/chart/line'
import 'echarts/lib/component/tooltip'
import debounce from 'lodash.debounce'
import GButton from '@/components/common/g-button'
import { dashboard as dashboardAPI } from '@/api'
import { format } from '@/utils/date'

const apiList = [
    {
        key: 'all',
        name: '总计',
        color: '#F7BA2A'
    },
    {
        key: 'data',
        name: '数据服务',
        color: '#20A0FF'
    },
    {
        key: 'public_data',
        name: '公共数据',
        color: '#13CE66'
    },
    {
        key: 'geom',
        name: '几何分析',
        color: '#8492A6'
    },
    {
        key: 'geocoding',
        name: '地理编码',
        color: '#ed3f14'
    },
    {
        key: 'routing',
        name: '路径分析',
        color: '#749f83'
    },
    {
        key: 'mapping',
        name: '地图服务',
        color: '#bda29a'
    },
    {
        key: 'dataviz',
        name: '数据可视化',
        color: '#f57828'
    },
]

const rangeList = [
    {
        key: 'day',
        name: '24小时',
        unit: 'hour',
        count: 24
    },
    {
        key: 'week',
        name: '7天',
        unit: 'day',
        count: 7
    },
    {
        key: 'month',
        name: '30天',
        unit: 'day',
        count: 30
    },
]

const option = {
    grid: {
        top: 10,
        bottom: 0,
        right: 0,
        left: 0,
        containLabel: true
    },
    tooltip: {
        trigger: 'axis',
        extraCssText: `
            background: #fff;
            box-shadow: 0 0 3px rgba(0, 0, 0, 0.3);
            border-radius: 0;
            color: #000;
            font-size: 12px;
            padding: 10px 12px;
        `,
        formatter: function ( params ) {
            let arr = params[ 0 ].name.split( ',' );
            let date = format( Number( arr[ 0 ] ), arr[ 1 ] )
            return `
                <p>${ date }</p>
                <p style="font-weight: 600; color:${ params[ 0 ].color }">${ params[ 0 ].seriesName } - ${ params[ 0 ].value }</p>
                `;
        }
    },
    xAxis: [
        {
            type: 'category',
            axisTick: {
                show: false
            },
            axisLine: {
                show: false
            },
            axisPointer: {
                type: 'line',
                lineStyle: {
                    opacity: 0
                }
            },
            axisLabel: {
                textStyle: {
                    color: 'rgba(9, 17, 32, .45)'
                },
                formatter: function( value, index ) {
                    return value.split( ',' )[ 2 ];
                },
            },
            data: []
        }
    ],
    yAxis: [
        {
            type: 'value',
            axisTick: {
                show: false
            },
            axisLine: {
                show: false
            },
            splitLine: {
                show: false
            },
            axisLabel: {
                inside: true,
                textStyle: {
                    color: 'rgba(9, 17, 32, .45)'
                }
            }
        }
    ],
    series: [
        {   
            name: '',
            type:'line',
            smooth: true,
            symbolSize: 6,
            showSymbol: false,
            itemStyle: {
                normal: {
                    color: '#F7BA2A'
                }
            },
            label: {
                normal: {
                    show: true
                }
            },
            lineStyle: {
                normal: {
                    color: '#F7BA2A'
                }
            },
            areaStyle: {
                normal: {
                    color: '#F7BA2A',
                    opacity: 0.5
                }
            },
            data: []
        }
    ]
};

const setColor = ( option, color ) => {
    let item = option.series[ 0 ];
    item.itemStyle.normal.color = color;
    item.lineStyle.normal.color = color;
    item.areaStyle.normal.color = color;

    Vue.set( option.series, 0, item );

    return option;
}

const setRange = ( option, range ) => {

    let xAxis = option.xAxis[ 0 ];
    let data = [];
    let now = new Date();
    let D = now.getDate();
    let h = now.getHours();

    if ( range.unit === 'hour' ) {
        for ( let i = 0; i < range.count; i++ ) {
            let date = new Date();
            date.setHours( h - i );
            data.unshift( `${ date.getTime() },Y-MM-DD hh时,${ date.getHours() + '时' }` );
        }
    } else if ( range.unit === 'day' ) {
        let unit = range.count > 20 ? '' : '日';
        for ( let i = 0; i < range.count; i++ ) {
            let date = new Date();
            date.setDate( D - i - 1 );
            let label = range.count === 7 ? format( date, 'M月D日' ) : date.getDate()
            data.unshift( `${ date.getTime() },Y-MM-DD,${ label }` );
        }
    }

    xAxis.data = data;
    Vue.set( option.xAxis, 0, xAxis );

    return option;

} 

const setData = ( option, data, name ) => {
    let item = option.series[ 0 ];
    item.data = data;
    item.name = name;

    Vue.set( option.series, 0, item );

    return option;
}

let pendingHandler;

export default {
    name: 'dashboard-resource',
    data () {
        return {
            chart: null,
            pending: false,
            error: false,
            apiList,
            rangeList,
            option,
            selected: 'all',
            rangeSelected: 'day'
        }
    },
    mounted () {

        if ( this.chart ) return;

        this.chart = echarts.init( this.$refs.chart );
        this.chart.setOption( this.option );

        const resizeHanlder = debounce( () => {
                this.chart.resize()
            }, 100, { leading: true } );

        this.$root.$on( 'sidebar-toggle', resizeHanlder );
        window.addEventListener( 'resize', resizeHanlder, false );

        this.update();
    },
    methods: {
        selectType ( api ) {
            this.selected = api.key;
            this.update();
        },
        selectRange ( range ) {
            this.rangeSelected = range.key;
            this.update();
        },
        update () {
            let selected = this.apiList.find( item => item.key === this.selected );
            let rangeSelected = this.rangeList.find( item => item.key === this.rangeSelected );

            let promise = dashboardAPI.getAPIStatistics( selected.key, rangeSelected.unit, rangeSelected.count )

            // this.pending = true;
            this.error = false;

            clearTimeout( pendingHandler );
            pendingHandler = setTimeout( () => {
                this.pending = true;
            }, 800 );

            let type = selected.key;    // 防止频繁切换类型时加载错误的数据

            promise.then( res => {

                clearTimeout( pendingHandler );

                if ( this.selected !== type ) return;
                if ( res.data.code === 0 ) {
                    this.option = setRange( this.option, rangeSelected );
                    this.option = setData( this.option, res.data.data, selected.name );
                    this.option = setColor( this.option, selected.color );
                    this.chart.setOption( this.option );
                } else {
                    this.error = true;
                }
                this.pending = false;
            } ).catch( err => {

                clearTimeout( pendingHandler );

                if ( this.selected !== type ) return;
                this.pending = false;
                this.error = true;
            } )
        }
    },
    components: {
        GButton
    }
}
</script>

<style lang="scss">
@import 'common';
.dashboard-resource {
    width: 100%;

    .resource-header {
        margin-bottom: 10px;
        position: relative;

        &::after {
            @include clearfix();
        }

        .resource-type {
            float: left;
            margin-left: 5px;
            // border-bottom: 1px solid $bdGray;
            position: relative;

            &::before {
                content: '';
                display: block;
                width: 100%;
                position: absolute;
                bottom: 0;
                border-bottom: 1px solid $bdGray;
            }

            &::after {
                @include clearfix();
            }

            .resource-type-item {
                float: left;
                height: 40px;
                line-height: 38px;
                border-bottom: 2px solid transparent;
                padding: 0 10px 0 14px;
                position: relative;
                cursor: pointer;
                transition: all .3s;
                color: #888;

                &.active {
                    color: $primary;
                    border-color: $primary;
                }

                .resource-type-item-legend {
                    display: inline-block;
                    background: red;
                    width: 6px;
                    height: 6px;
                    border-radius: 50%;
                    position: absolute;
                    top: 50%;
                    left: 0;
                    margin-left: 3px;
                    margin-top: -3px;
                }
            }
        }

        .resource-timerange {
            float: right;
            margin: 5px 0;
            position: absolute;
            top: 5px;
            right: 0;
            text-align: center;

            &::after {
                @include clearfix();
            }

            .resouce-timerange-box {
                border-radius: 3px;
                overflow: hidden;
                display: inline-block;

                .resource-timerange-item {
                    float: left;
                    height: 30px;
                    line-height: 28px;
                    padding: 0 12px;
                    color: $white;
                    background-color: lighten( $primary, 5% );
                    cursor: pointer;
                    transition: background-color .2s;
                    
                    &:hover,
                    &.active {
                        background-color: $darkPrimary;
                    }
                }
            }
        }

        @media screen and (max-width: 1000px) {
            .resource-type {
                margin-right: 200px;
                margin-bottom: 10px;
                text-align: center;

                .resource-type-item {
                    float: none;
                    display: inline-block;
                    // width: 94px;
                }
            }
        }

        @media screen and (max-width: 800px) {
            .resource-type {
                width: 100%;
                margin-right: 0;
                margin-bottom: 10px;
                text-align: center;

                .resource-type-item {
                    float: none;
                    display: inline-block;
                    // width: 94px;
                }
            }

            .resource-timerange {
                position: static;
                width: 100%;
            }
        }
    }

    .resource-content {
        width: 100%;
        height: 300px;
        position: relative;

        .resouce-loading {
            color: $primary;
            position: absolute;
            top: 0;
            left: 0;
            z-index: 20;
            width: 100%;
            height: 100%;
            background-color: $bgWhite;
            border-bottom: 1px solid $bdGray;

            > i {
                font-size: 22px;
                width: 50px;
                height: 50px;
                position: absolute;
                top: 50%;
                left: 50%;
                margin-top: -25px;
                margin-left: -25px;
                text-align: center;
                line-height: 50px;
            }
        }

        .resource-chart {
            width: 100%;
            height: 100%;
        }
    }
}
</style>
